
export default class UDP {

  constructor(host, port) {
    this.host = host;
    this.port = port;
    this.socket = null;
  }

  /**
   * 初始化socket对象
   * @returns {Promise<void>}
   */
  async init() {
    if (plus.os.name === 'Android') {
      const Context = plus.android.importClass("android.content.Context");
      const DatagramSocket = plus.android.importClass("java.net.DatagramSocket");
      const InetAddress = plus.android.importClass("java.net.InetAddress");

      const socket = new DatagramSocket();
      const address = InetAddress.getByName(this.host);
      socket.connect(address, this.port);
      this.socket = socket;
    } else if (plus.os.name === 'iOS') {
      const socket = plus.ios.createSocket({
        type: "UDP",
        host: this.host,
        port: this.port,
        callback: function () {
          console.log('socket callback');
        }
      });
      this.socket = socket;
    }
  }

  /**
   * 发送数据
   * @param data {string} 数据
   * @returns {Promise<void>}
   */
  async send(data, receive, bufferSize = 1024) {
    if (plus.os.name === 'Android') {
      const DatagramPacket = plus.android.importClass("java.net.DatagramPacket");

      const packet = new DatagramPacket(data.getBytes(), data.getBytes().length);
      this.socket.send(packet);
	  
	  const buffer = new ArrayBuffer(bufferSize);
	  const receivePacket = new DatagramPacket(buffer, buffer.byteLength);
	  this.socket.receive(receivePacket);
	  const receiveData = new Uint8Array(receivePacket.getData(), 0, receivePacket.getLength());

	  if (receive) {
			receive(receiveData);
	    }
    } else if (plus.os.name === 'iOS') {
      this.socket.send({
        data: data,
        callback: function () {
          console.log('send callback');
        }
      });
	  
	  this.socket.receive({
	    bufferSize: bufferSize,
	    callback: function (data) {
	      // const message = plus.ios.convertArrayBufferToString(data);
	      const receiveData = new Uint8Array(data);
	      if (receive) {
	      			receive(receiveData);
	        }
	    }
	  });
    }
  }

  /**
   * 关闭socket对象
   * @returns {Promise<void>}
   */
  async close() {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }
}
